import socketserver
import threading
import datetime
import logging


FORMAT = '%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)


class ChatHandler(socketserver.StreamRequestHandler):

    def setup(self):
        super().setup()
        self.event = threading.Event()
        self.lock = threading.Lock()
        server.clients[self.client_address] = self.wfile, self.request

    def handle(self):
        super().handle()
        print('-' * 30)
        print(server.clients.values())
        while not self.event.is_set():

            logging.info(self.request)
            try:
                data = self.rfile.readline().strip().decode()
                print(data)

                if data == '' or data == 'quit':
                    server.clients.pop(self.client_address)
                    self.finish()
                    break
                logging.info('receive data: {}'.format(data))

                msg = '{:%Y/%m/%d %H:%M:%S} {}:{} {}'.format(
                    datetime.datetime.now(),
                    *self.client_address,
                    data
                ).encode()
                for wf, _ in server.clients.values():
                    wf.write(msg)
                    wf.flush()
            except Exception:
                pass

    def finish(self):
        super().finish()
        self.event.set()


server = socketserver.ThreadingTCPServer(('10.70.1.192', 60000), ChatHandler)
server.clients = {}
# server.daemon_threads = True
threading.Thread(target=server.serve_forever, name='Chatserver', daemon=True).start()


while True:
    cmd = input('>>> ').strip()
    if cmd == 'quit':
        server.server_close()
        break
    print(threading.enumerate())
